﻿/// Write a program that finds the index of given element in a sorted array of integers 
/// by using the binary search algorithm (find it in Wikipedia).




using System;

class zad_11
{
    
    static void Main()
    {
        int[] arr = { 1, 2, 3, 5, 7, 30, 76, 110 }; //{ 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 }; //{ 2, 2, 2, 1, 1, 2, 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 5 };
        
        int searchKey = 110;

        int foundAtIndex = binarySearch(arr, searchKey);

        Console.WriteLine(foundAtIndex);
    }

    private static int binarySearch(int[] arr, int searchKey)
    {
        int min = 0;
        int max = arr.Length - 1;
        int mid = 0;
        int foundAtIndex = -1;

        while (min <= max)
        {
            mid = min + (max - min) / 2;

            if (searchKey == arr[mid])
            {
                return mid;
            }
            else if (searchKey < arr[mid])
            {
                max = mid - 1;
            }
            else
            {
                min = mid + 1;
            }

        }
        return foundAtIndex;
    }
}
